Grokking Microsoft Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Microsoft Easy Problems
Buddy Strings (easy)
Solution: Buddy Strings
Can Place Flowers (easy)
Solution: Can Place Flowers
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Maximum Number of Balloons (easy)
Solution: Maximum Number of Balloons
Binary Tree Path Sum (easy)
Solution: Binary Tree Path Sum
Pair with Target Sum (easy)
Solution: Pair with Target Sum
Buy Two Chocolates (easy)
Solution: Buy Two Chocolates
Root Equals Sum of Children (easy)
Solution: Root Equals Sum of Children
Excel Sheet Column Title (easy)
Solution: Excel Sheet Column Title
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Min Cost Climbing Stairs (easy)
Solution: Min Cost Climbing Stairs
Plus One (easy)
Solution: Plus One
Intersection of Two Arrays (easy)
Solution: Intersection of Two Arrays
Find the Index of the First Occurrence in a String (easy)
Solution: Find the Index of the First Occurrence in a String
Merge Two Sorted Lists (easy)
Solution: Merge Two Sorted Lists
Microsoft Medium Problems
Nth Digit (medium)
Solution: Nth Digit
Restore IP Addresses (medium)
Solution: Restore IP Addresses
Find Original Array From Doubled Array (medium)
Solution: Find Original Array From Doubled Array
Reverse Words in a String II (medium)
Solution: Reverse Words in a String II
Longest Arithmetic Subsequence (medium)
Solution: Longest Arithmetic Subsequence
Matchsticks to Square (medium)
Solution: Matchsticks to Square
Score of Parentheses (medium)
Solution: Score of Parentheses
Maximum Length of a Concatenated String with Unique Characters (medium)
Solution: Maximum Length of a Concatenated String with Unique Characters
Inorder Successor in BST (medium)
Solution: Inorder Successor in BST
Distribute Coins in Binary Tree (medium)
Solution: Distribute Coins in Binary Tree
Spiral Matrix (medium)
Solution: Spiral Matrix
Delete Node in a BST (medium)
Solution: Delete Node in a BST
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Rotate Image (medium)
Solution: Rotate Image
Combinations (medium)
Solution: Combinations
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Multiply Strings (medium)
Solution: Multiply Strings
Best Time to Buy and Sell Stock II (medium)
Solution: Best Time to Buy and Sell Stock II
Largest Palindromic Number (medium)
Solution: Largest Palindromic Number
Remove Duplicate Letters (medium)
Solution: Remove Duplicate Letters
Next Permutation (medium)
Solution: Next Permutation
132 Pattern (medium)
Solution: 132 Pattern
Valid Sudoku (medium)
Solution: Valid Sudoku
Number of Islands (medium)
Solution: Number of Islands
Buildings With an Ocean View (medium)
Solution: Buildings With an Ocean View
Microsoft Hard Problems
Regular Expression Matching (hard)
Solution: Regular Expression Matching
First Missing Positive (hard)
Solution: First Missing Positive
Largest Rectangle in Histogram (hard)
Solution: Largest Rectangle in Histogram
Sliding Window Maximum (hard)
Solution: Sliding Window Maximum
Count Unique Characters of All Substrings of a Given String (hard)
Solution: Count Unique Characters of All Substrings of a Given String
Word Ladder (hard)
Solution: Word Ladder
Word Ladder II (hard)
Solution: Word Ladder II
Number of Flowers in Full Bloom (hard)
Solution: Number of Flowers in Full Bloom
Median of Two Sorted Arrays (hard)
Solution: Median of Two Sorted Arrays
Longest Valid Parentheses (hard)
Solution: Longest Valid Parentheses
Solution: Count Unique Characters of All Substrings of a Given String

Problem Statement

Given a string s, return the sum of unique characters in all possible substrings of a given string. You also need to count the unique characters of repeating substrings.

Examples

  • Example 1:

    • Input: "aac"
    • Expected Output: 8
    • Justification: The substrings are "a", "a", "c", "aa", "ac", "aac". Their unique characters count are 1, 1, 1, 0, 2, 1 respectively. Summing up the unique characters: 1 + 1 + 1 + 0 (from "aa") + 2 (from "ac") + 1 (from "aac") = 6.
  • Example 2:

    • Input: "aaa"
    • Expected Output: 6
    • Justification: The substrings are "a", "a", "a", "aa", "aa", and "aaa". Their unique characters count are 1, 1, 1, 0, 0, 0 respectively. So, there are total 3 unique characters in all substrings.
  • Example 3:

    • Input: "abca"
    • Expected Output: 18
    • Justification: The substrings and their unique character counts are as follows: "a" (1), "b" (1), "c" (1), "a" (1), "ab" (2), "bc" (2), "ca" (2), "abc" (3), "bca" (3), "abca" (2). The sum of unique characters is 18.

Solution

The solution to the problem of counting unique characters of all substrings of a given string employs an efficient strategy that leverages the positioning of characters within the string. Rather than enumerating all possible substrings, which would be computationally expensive, the approach calculates the contribution of each character based on its occurrence positions. This is done by maintaining a record of the last two positions where each character was found. By considering the distance between these occurrences and their positions relative to the string's start and end, we can determine how many unique substrings each character contributes to without direct enumeration. This method significantly reduces the computational complexity, making it feasible to handle strings of considerable length.

The algorithm iterates through the string once, updating the contribution of each character as it proceeds. This is achieved by maintaining a two-dimensional array where each row corresponds to a character of the alphabet and contains the last two positions of that character's occurrence. By calculating the contribution of characters based on the differences between their last positions and their position in the current iteration, the algorithm efficiently aggregates the total count of unique characters across all substrings. The final step involves adjusting this count to include contributions from substrings that end with each character, ensuring that all unique characters are accounted for.

Step-by-Step Algorithm

  1. Initialize a 2D array index with dimensions 26x2 to store the last two positions for each alphabet character, initializing all values to -1.
  2. Initialize variables res (for the result) and mod (for modular arithmetic to prevent overflow) with appropriate values.
  3. Iterate through each character of the input string, performing the following steps:
    • Convert the current character to an index corresponding to its position in the alphabet (0-25).
    • Update res by adding the product of the difference between the current position and the character's last occurrence, and the difference between its last two occurrences. Apply modulo operation to prevent overflow.
    • Update the index array for the current character to reflect its new last occurrence and the previous last occurrence.
  4. After iterating through the string, make a final pass over the alphabet characters to adjust res by accounting for substrings that end with each character. This involves adding the contribution of substrings that extend to the end of the string from each character's last occurrence.
  5. Return res as the total count of unique characters across all substrings.

Algorithm Walkthrough

Let's consider the input: s = "ABCA"

  1. Initialize index as a 2D array with all values set to -1, res to 0, N to 4 (length of "ABCA"), and mod to (10^9 + 7).
  2. For character 'A' at position 0:
    • 'A' converts to index 0. Its last positions update from [-1, -1] to [-1, 0].
    • res updates by adding (0 - (-1)) * ((-1) - (-1)) % mod which simplifies to 0.
  3. For character 'B' at position 1:
    • 'B' converts to index 1. Its last positions update from [-1, -1] to [-1, 1].
    • res updates by adding (1 - (-1)) * ((-1) - (-1)) % mod which simplifies to 0.
  4. For character 'C' at position 2:
    • 'C' converts to index 2. Its last positions update from [-1, -1] to [-1, 2].
    • res updates by adding (2 - (-1)) * ((-1) - (-1)) % mod which simplifies to 0.
  5. For character 'A' at position 3:
    • 'A' converts to index 0 again. Its last positions update from [-1, 0] to [0, 3].
    • res updates by adding (3 - 0) * (0 - (-1)) % mod which simplifies to 3.
  6. Final adjustment for 'A':
  • For 'A': The adjustment involves calculating the contribution from the last occurrence (index 3) to the end of the string. The calculation (4 - 3) * (3 - 0) % mod adds to res. So, res becomes 6.
  • For 'B': The adjustment for 'B' involves the substring ending with 'B', calculated as (4 - 1) * (1 - (-1)) % mod, contributing to res. So, res updates to 12.
  • For 'C': Similarly, the adjustment for 'C' is (4 - 2) * (2 - (-1)) % mod, contributing to res. So, es updates to 18.
  1. The final value of res is 18.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity:

The code iterates through each character of the string exactly once to calculate its contribution to the result. This leads to a linear iteration with complexity.

Space Complexity:

  • The space used by the index array is constant, as it always contains 26 elements, each of which has 2 integers. This size does not change regardless of the input string's length, resulting in space complexity.
Count Unique Characters of All Substrings of a Given String (hard)
Word Ladder (hard)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity:

Space Complexity: